﻿using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using Service.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Compilation;
using System.Web.Http;
using System.Web.Mvc;

namespace WebApplication1
{
    /// <summary>
    /// Autofac依赖注入配置
    /// </summary>
    public class AutofacConfig
    {
        /// <summary>
        /// 初始化
        /// </summary>
        public static void Initialise()
        {
            var builder = RegisterService();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public static void InitialiseWebApi()
        {
            var builder = RegisterServiceWebApi();
            // Set the dependency resolver for Web API.
            var webApiResolver = new AutofacWebApiDependencyResolver(builder.Build());
            GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
        }

        /// <summary>
        /// 注入实现
        /// </summary>
        /// <returns></returns>
        private static ContainerBuilder RegisterService()
        {
            var builder = new ContainerBuilder();


            ServiceConfig.Buider.InitIoc(builder);

            // Mvc Register
            builder.RegisterControllers(Assembly.GetExecutingAssembly()).AsSelf().PropertiesAutowired();
            builder.RegisterFilterProvider();

            return builder;
        } /// <summary>
      
        /// 注入实现
        /// </summary>
        /// <returns></returns>
        private static ContainerBuilder RegisterServiceWebApi()
        {
            var builder = new ContainerBuilder();


            ServiceConfig.Buider.InitIoc(builder);

            //WebApi Register
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).AsSelf().PropertiesAutowired();
            builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
            builder.RegisterWebApiModelBinderProvider(); 
           

            return builder;
        }
    }
}